package cn.o.app.json;

import java.util.Date;

import cn.o.app.json.JSONField.Type;
import cn.o.app.reflect.OField;
import cn.o.app.util.ODateFormat;

@SuppressWarnings("serial")
public class JsonDate extends Date implements IJsonItem {

	protected Type mType = Type.STRING;

	// 用于JSON序列化和反序列化
	// protected String mJsonFormat = "yyyy-MM-dd'T'HH:mm:ss";

	protected String mJsonFormat = "yyyy-MM-dd HH:mm";
	String mShortFormat = "yyyy-MM-dd";
	// 用于格式化输出，覆盖toString()
	// protected String mFormat = "yyyy-MM-dd'T'HH:mm:ss";
	protected String mFormat = "yyyy-MM-dd HH:mm";
	protected String mLocalFormat = "yyyy年MM月dd日";

	@Override
	public IJsonItem fromJson(Object json, OField itemField) {
		init(itemField);
		String str = json.toString();
		if (str == null || str.trim().equals("")) {
			return null;
		} else {
			try {
				if (mType == Type.STRING) {
					this.setTime(ODateFormat
							.parse(json.toString(), mJsonFormat).getTime());
				} else {
					this.setTime(Long.parseLong(json.toString()));
				}
			} catch (Exception e) {

			}
		}
		return this;
	}

	@Override
	public Object toJson(OField itemField) {
		init(itemField);
		if (mType == Type.STRING) {
			return ODateFormat.format(this, mJsonFormat);
		} else {
			return this.getTime();
		}
	}

	protected void init(OField itemField) {
		if (itemField != null) {
			JSONField jsonField = itemField.getAnnotation(JSONField.class);
			if (jsonField != null) {
				mType = jsonField.type();
				mJsonFormat = jsonField.format();
			}
		}
	}

	public Type getType() {
		return mType;
	}

	public void setType(Type type) {
		mType = type;
	}

	public String getJsonFormat() {
		return mJsonFormat;
	}

	public void setJsonFormat(String jsonFormat) {
		mJsonFormat = jsonFormat;
	}

	public String getFormat() {
		return mFormat;
	}

	public void setFormat(String format) {
		mFormat = format;
	}

	@Override
	public String toString() {
		if (mFormat == null) {
			return super.toString();
		} else {
			return ODateFormat.format(this, mFormat);
		}
	}

	public String toLocalString() {
		return ODateFormat.format(this, mLocalFormat);
	}

	public String toShotString() {
		return ODateFormat.format(this, mShortFormat);
	}
}
